package com.serverdemo.application.scene;

import com.serverdemo.application.common.LSEnterSceneRequest;
import com.serverdemo.application.common.MessageIDConst;
import com.serverdemo.application.common.PacketIDConst;
import com.serverdemo.core.entity.SocketEntity;
import com.serverdemo.core.entity.SocketEntityStatusEnum;
import com.serverdemo.core.processor.AbstractProcessor;
import com.serverdemo.core.processor.AbstractProcessorMessage;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by wangqiang on 2020/4/10.
 */
public class SceneProcessor extends AbstractProcessor
{
    /**
     * 场景里的所有玩家
     * key: username, value:Player
     */
    private HashMap<String, Player> players = new HashMap<String, Player>();

    @Override
    public void init()
    {
        super.init();
    }

    @Override
    public void tick(int interval)
    {
        super.tick(interval);

        tickPlayer(interval);
    }

    private void tickPlayer(int interval)
    {
        Iterator<Map.Entry<String, Player>> iterator = players.entrySet().iterator();
        while (iterator.hasNext())
        {
            Map.Entry<String, Player> next = iterator.next();
            Player player = next.getValue();

            if (player.getEntityStatus() == SocketEntityStatusEnum.EXCEPTION)
            {
                player.setSocketEntity(null);
                iterator.remove();
                continue;
            }

            player.processInput(interval);

            player.processOutput(interval);
        }
    }

    public void dispatchMessage(AbstractProcessorMessage message)
    {
        int messageID = message.getMessageID();
        switch (messageID)
        {
            case MessageIDConst
                    .LS_ENTER_SCENE_REQUEST:
            {
                LSEnterSceneRequest request = (LSEnterSceneRequest) message;
                playerEnterScene(request.getUserName(), request.getSocketEntity(), request.getData());
                break;
            }
            default:
            {
                break;
            }
        }
    }

    private void playerEnterScene(String userName, SocketEntity socketEntity, String data)
    {
        if (players.containsKey(userName))
        {
            return;
        }

        Player player = new Player();
        player.setSocketEntity(socketEntity);
        player.setData(data);
        player.setUserName(userName);
        player.setSceneProcessor(this);

        players.put(userName, player);

        // 给玩家发送进入成功消息
        SCEnterSceneResponse response = new SCEnterSceneResponse();
        response.setResult(0);
        response.setUserName(userName);
        player.sendNetPacket(PacketIDConst.SC_ENTER_SCENE_RESPONSE, response);
    }

    public int getPlayerCount()
    {
        return players.size();
    }

}
